package com.security.demo.dao;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.security.demo.model.Resource;


@Repository
public class ResourceDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Resource findOne(String resourceId) {
        final String sql =
                "select id, name, type, url, parent_id, parent_ids, permission, available from t_resource where id = ?";
        List<Resource> resourceList = jdbcTemplate.query(sql,
                new BeanPropertyRowMapper<Resource>(Resource.class), resourceId);
        return CollectionUtils.isNotEmpty(resourceList) ? resourceList.get(0) : null;
    }

    public List<Resource> findChildren(String resourceId) {
        final String sql =
                "select id, name, type, url, parent_id, parent_ids, permission, available from t_resource where parent_id = ?";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<Resource>(Resource.class),
                resourceId);
    }

    public List<Resource> findAll() {
        final String resourceSql =
                "select id, name, type, url, parent_id, parent_ids, permission, available from t_resource order by concat(parent_ids, id) asc";
        return jdbcTemplate.query(resourceSql, new BeanPropertyRowMapper<Resource>(Resource.class));
    }

    public List<Resource> findMenus() {
        final String resourceSql =
                "select id, name, type, url, parent_id, parent_ids, permission, available from t_resource where type = ? order by concat(parent_ids, id) asc";
        return jdbcTemplate.query(resourceSql, new Object[] {"menu"},
                new BeanPropertyRowMapper<Resource>(Resource.class));
    }
    
    
    public Resource findByUrl(String url) {
        final String sql =
                "select id, name, type, url, parent_id, parent_ids, permission, available from t_resource where url = ?";
        List<Resource> resourceList = jdbcTemplate.query(sql,
                new BeanPropertyRowMapper<Resource>(Resource.class), url);
        return CollectionUtils.isNotEmpty(resourceList) ? resourceList.get(0) : null;
    }

}
